/*
 * @brief 光照传感器
 */

#include <rtthread.h>
#include <rtdevice.h>

#include <sensor_bh1750.h>

#define DBG_TAG "bh1750.c"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

static struct rt_i2c_bus_device *i2c_bus = RT_NULL;
float lightVal = 0.0f;

/**
 * @brief  向I2C从设备寄存器中写数据
 * @param  *bus -> I2C设备对象句柄
 * @param  reg -> 寄存器
 * @param  *data -> 数据
 * @return 是否写入成功
 */
static rt_err_t write_reg(struct rt_i2c_bus_device *bus, rt_uint8_t reg, rt_uint8_t *data)
{
    rt_uint8_t buf[4] = { 0 };
    struct rt_i2c_msg msgs;
    buf[0] = reg;
    msgs.addr = BH1750_SlaveAddress;
    msgs.flags = RT_I2C_WR;
    msgs.buf = buf;
    msgs.len = 1;
    if (rt_i2c_transfer(bus, &msgs, 1) == 1)
        return RT_EOK;
    else
        return -RT_ERROR;
}

/**
 * @brief  读取I2C从设备寄存器数据
 * @param  *bus -> I2C设备对象句柄
 * @param  len -> 读取数据长度
 * @param  *buf -> 读取数据
 * @return 是否读取成功
 */
static rt_err_t read_regs(struct rt_i2c_bus_device *bus, rt_uint8_t len, rt_uint8_t *buf)
{
    struct rt_i2c_msg msgs;
    msgs.addr = BH1750_SlaveAddress;
    msgs.flags = RT_I2C_RD;
    msgs.buf = buf;
    msgs.len = len;
    if (rt_i2c_transfer(bus, &msgs, 1) == 1)
        return RT_EOK;
    else
        return -RT_ERROR;
}

/**
 * @brief  读取光照度值
 * @param  无
 * @return 光照度值
 */
float bh1750_get_data(void)
{
    rt_uint8_t temp[2] = { 0 };
    write_reg(i2c_bus, BH1750_H1MODE, 0);
    rt_thread_mdelay(200);
    read_regs(i2c_bus, 2, temp);
    lightVal = (temp[0] << 8 | temp[1]) / 1.2f;
    return lightVal;
}

/**
 * @brief  bh1750_init初始化
 * @param  无
 * @return 初始化是否成功
 */
int bh1750_init(void)
{
    i2c_bus = (struct rt_i2c_bus_device *) rt_device_find(BH1750_I2C_BUS_NAME);
    if (i2c_bus == RT_NULL)
    {
        LOG_E("failed to find %s device!\n", BH1750_I2C_BUS_NAME);
        return -1;
    }
    write_reg(i2c_bus, BH1750_POWER, 0);
    return 0;
}
